import './Category.scss';
import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux'
import ReactSwipe from 'react-swipe';
import getCategoryApi from '../../actions/categoryAction.js'
/**
 * @constructor <Category />
 * @description
 */
class Category extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      swiperCurrentIndex: 0, // 轮播菜单初始位置
      list: []
    }
    this.fetchData();
  }

  fetchData() {
    // 获取分类列表，并设置进入 redux Store
    this.props.getCategoryAction()
  }


  // 去分类页面
  toCategory() {
    window.location.href = '/category.html'
  }

  renderItems() {
    let items = this.props.categoryReducer;
    // 复制数组防止引用
    let _items = JSON.parse(JSON.stringify(items));
    var resultArr = [];
    for (var i = 0; i < _items.length; i += 8) {
      resultArr.push(items.slice(i, i + 8));
    }
    return resultArr.map((item, index) => {
      return (
        <div className="carousel-item" key={index + 1}>
          {
            item.map((item1, index1) => {
              return (
                <div className="category-item" key={index1 + 10} onClick={this.toCategory}>
                  <img className="item-icon" src={item1.url}/>
                  <p className="item-name">{item1.name}</p>
                </div>
              )
            })
          }
        </div>
      )
    })
  }

  render() {
    const opt = {
      startSlide: 0,
      continuous: true,
      disableScroll: false,
      stopPropagation: false,
      callback: function(index) {
        this.setState({swiperCurrentIndex: index});
      }.bind(this)
    }
    return (<div className="category-content clearfix">
      <ReactSwipe className="swiper-con" swipeOptions={opt}>
        {
          this.renderItems()
        }
      </ReactSwipe>
      <div className="index-container">
        <ul>
          <li className={this.state.swiperCurrentIndex == 0
              ? "selected"
              : ''}></li>
          <li className={this.state.swiperCurrentIndex == 1
              ? "selected"
              : ''}></li>
        </ul>
      </div>
    </div>);
  }
}

export default connect((state) => {
  return {categoryReducer: state.categoryReducer.items}
}, (dispatch) => {
  return {
    getCategoryAction: bindActionCreators(getCategoryApi, dispatch)
  }
})(Category);
